<!-- eslint-disable no-console -->
<!-- 排班管理模块 - 排班计划 -->
<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { CalplanApi, DictApi } from '#/api';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteCalplan, DictResp, getCalplanList } from '#/api';
import { getToolBarBtns, setToolBarBtnDefaultDisabled } from '#/utils';

import { confirm, messageSuccess } from '../../wm/common/common';
import editModal from './edit-modal.vue';
// import {} from 'element-plus';
// 将字典数据添加到数组中;
const mes_calendar_type = reactive<DictApi.SelectOption[]>([]);
const mes_shift_method = reactive<DictApi.SelectOption[]>([]);
const mes_shift_type = reactive<DictApi.SelectOption[]>([]);
const mes_order_status = reactive<DictApi.SelectOption[]>([]);
DictResp([
  'mes_calendar_type',
  'mes_shift_method',
  'mes_shift_type',
  'mes_order_status',
]).then((res) => {
  // 将两个数组合并
  if (res.mes_calendar_type) {
    mes_calendar_type.push(...res.mes_calendar_type);
  }
  if (res.mes_shift_method) {
    mes_shift_method.push(...res.mes_shift_method);
  }
  if (res.mes_shift_type) {
    mes_shift_type.push(...res.mes_shift_type);
  }
  if (res.mes_order_status) {
    mes_order_status.push(...res.mes_order_status);
  }
});

// 存储选中行的响应式变量
const selectedRows = ref<CalplanApi.Row[]>([]);

const [EditModal, editmodalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: editModal,
  destroyOnClose: true,
  onClosed() {
    gridApi.query();
  },
});

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: mes_calendar_type,
        placeholder: '请选择班组类型',
      },
      fieldName: 'calendarType',
      label: '班组类型',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入计划编号',
      },
      fieldName: 'planCode',
      label: '计划编号',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入计划名称',
      },
      fieldName: 'planName',
      label: '计划名称',
    },
    {
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择开始日期',
      },
      fieldName: 'startDate',
      label: '开始日期',
    },
    {
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择结束日期',
      },
      fieldName: 'endDate',
      label: '结束日期',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
// 表格左上角按钮
const buttons = getToolBarBtns();
const gridOptions: VxeGridProps<CalplanApi.Row> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    {
      align: 'left',
      field: 'planId',
      title: '',
      type: 'checkbox',
      width: 50,
    },
    {
      field: 'planCode',
      title: '计划编号',
      cellRender: { name: 'CellButtonInfo', props: { onClick: editRowEvent } },
    },
    { field: 'planName', title: '计划名称' },
    {
      field: 'calendarType',
      title: '班组类型',
      formatter: ({ cellValue }) => {
        const item = mes_calendar_type.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    { field: 'startDate', title: '开始日期' },
    { field: 'endDate', title: '结束日期' },
    {
      field: 'shiftType',
      title: '轮班方式',
      formatter: ({ cellValue }) => {
        const item = mes_shift_type.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    {
      field: 'shiftMethod',
      title: '倒班方式',
      formatter: ({ cellValue }) => {
        const item = mes_shift_method.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    {
      field: 'status',
      title: '单据状态',
      formatter: ({ cellValue }) => {
        const item = mes_order_status.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    { slots: { default: 'action' }, title: '操作' },
  ],
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getCalplanList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },

  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    refresh: { code: 'query' },
    buttons: buttons.value,
  },
};

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    console.log(code);
    switch (code) {
      case 'myAdd': {
        // 新增逻辑
        console.log('新增');
        editmodalApi
          .setState({
            title: '添加排班计划',
          })
          .setData({ mes_shift_type, mes_shift_method, mes_calendar_type })
          .open();
        break;
      }
      case 'myDel': {
        // 删除逻辑
        console.log('删除');
        deleteRowEvent(selectedRows.value as any);
        break;
      }
      default: {
        break;
      }
    }
  },
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

function editRowEvent(row: CalplanApi.Row) {
  // console.log(row);
  editmodalApi
    .setState({
      title: '修改排班计划',
    })
    .setData({ row, mes_shift_type, mes_shift_method, mes_calendar_type })
    .open();
}
function deleteRowEvent(row: CalplanApi.Row) {
  const ids = Array.isArray(row)
    ? row.map((item) => item.planId)
    : [row.planId];
  const idString = ids.join(',');
  confirm(`确定要删除排班计划编号为${idString}的数据吗？`, '提示').then(() => {
    deleteCalplan(idString).then(() => {
      refreshGrid(`删除成功`);
    });
  });
}

function refreshGrid(msg: string) {
  messageSuccess(msg);
  gridApi.query();
}
</script>

<template>
  <div>
    <EditModal @success="refreshGrid" />
    <Grid>
      <template #action="{ row }">
        <VxeButton
          mode="text"
          icon="vxe-icon-signature"
          @click="editRowEvent(row)"
          status="primary"
          v-if="row.status === 'PREPARE'"
        >
          修改
        </VxeButton>
        <VxeButton
          icon="vxe-icon-delete"
          mode="text"
          @click="deleteRowEvent(row)"
          status="error"
          v-if="row.status === 'PREPARE'"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
  </div>
</template>
